package socket.example4;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @author lhn
 * @date 2024-04-25 15:39
 * 文件上传的客户端
 */

public class SocketTCP04FileUploadClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket(InetAddress.getLocalHost(),9999);
        System.out.println("客户端socket已启动");

        String filePath = "E:\\0.jpeg";
        //创建读取磁盘文件的输入流
        BufferedInputStream bufferedInputStream = new BufferedInputStream(
                new FileInputStream(filePath)
        );
        //bytes为filePath文件对应字节数组
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);

        //通过socket获取到输出流，将bytes数据发送给服务器
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(
                socket.getOutputStream()
        );
        bufferedOutputStream.write(bytes);  //将文件对应的字节数组的内容，写入到数据通道中
        socket.shutdownOutput();

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(socket.getInputStream())
        );
        String str = bufferedReader.readLine();
        System.out.println("客户端接收到消息" + str);
        bufferedReader.close();

        bufferedInputStream.close();
        bufferedOutputStream.close();
        socket.close();
    }
}
